<?php
namespace application\admin\panels;
use application\utilities\Utility;

class configure_users extends panel {
	public $name = 'Configure Users';
	protected $UserConfig;
	protected $deleted;
	
	public function __construct() {
		$this->UserConfig = new \application\models\UserConfig;
		
	}
	
	public function title() {
		return 'Configure / Users';
	}
	
	
	public function handleData() {
		if($_REQUEST['update_settings']) {
			$this->UserConfig->save();
			
			$this->addMessage('success', 'Configuration successfully updated.');
		}
		echo json_encode($this->messages);
	}
	
	
	public function sidebar() {
		return array(
			array(
				'title'=>'General',
				'sectionID'=>'general'
			),
			array(
				'title'=>'Data',
				'sectionID'=>'data'
			),
			array(
				'title'=>'User Groups',
				'sectionID'=>'user-groups'
			)
		);
	}
	
	
	public function editField() {
		$field = getQueryVar('field');
		$row = DB()->getRow("SELECT `cf_data_type`, `cf_column` FROM `cn_content_fields` WHERE `cf_id`='$field'");
		$dataType = $row->cf_data_type;
		ob_start();
		?>
		<form>
		<?php
		
			
		
		$dataType = 'application\\datatypes\\'.$dataType;
		$dataType::editForm(new \application\models\ContentField($field));
		?>
		</form>
		<?php
		$content = ob_get_clean();
		$return = array('content'=>$content);
		if(in_array($row->cf_column, array('user_id', 'user_username', 'user_email', 'user_password', 'user_level'))) {
			$return['hide_delete'] = TRUE;
		}
		
		echo json_encode($return);
		exit();
	}

	
	public function saveField() {
		$field = new \application\models\ContentField($_REQUEST['field_id']);
			
		if($_REQUEST['field_delete']) {
			$field->delete();
			$this->addMessage('success', 'Field deleted successfully.');
			
		}
		else {
			$field->setDisplayName($_REQUEST['field_display_name']);
			$field->setRequired($_REQUEST['field_required']);
			$field->setShow($_REQUEST['field_show']);
			$field->setDescription($_REQUEST['field_description']);
			$field->setAux($_REQUEST['field_aux']);
			$field->setShow($_REQUEST['field_show']);
			$field->save();
			$this->addMessage('success', 'Field updated successfully');
		}
		ob_start();
		$this->manageDataTable();
		$table = ob_get_clean();
		echo json_encode(array('messages'=>$this->messages, 'table'=>$table));
	}
	
	public function newField() {
		$field = new \application\models\ContentField;
		if($_REQUEST['type']) {
			$type = $_REQUEST['type'];
		}
		else {
			$type = 'user';
		}
		if($_REQUEST['field_display_name'] && $_REQUEST['field_data_type']) {
			$field->create(array(
				'displayName'=>$_REQUEST['field_display_name'],
				'dataType'=>$_REQUEST['field_data_type'],
				'required'=>$_REQUEST['field_required'],
				'description'=>$_REQUEST['field_description'],
				'default'=>$_REQUEST['field_default'],
				'aux'=>$_REQUEST['field_aux'],
				'contentType'=>$type
			));
			$field->add();
			$this->addMessage('success', 'Field added successfully.');
			$ID = $field->getId();
			
		}
		else {
			$this->addMessage('error', 'Your field must have a name and data type.');
		}
		
		ob_start();
		$this->manageDataTable();
		$table = ob_get_clean();
		
		echo json_encode(array('messages'=>$this->messages, 'table'=>$table));
	}
	
	protected function manageDataTable() {
		?>
		<table id="manage-data-table" class="admin-table" width="100%">
			<thead>
				<tr>
					<th width="50%">Name</th>
					<th width="50%">Type</th>
				</tr>
			</thead>
			<tfoot>
				<tr>
					<th width="50%">Name</th>
					<th width="50%">Type</th>
				</tr>
			</tfoot>
			<tbody>
				<?php $style = '';?>
				<?php $results = DB()->getResults("SELECT * FROM `cn_content_fields` WHERE `cf_content_type`='0' ORDER BY `cf_display_name`");
				foreach($results as $result) : 
				
				?>
				
				<tr<?=$style?> id="field-row-<?=$result->cf_id?>">
					<?php if(in_array($result->cf_data_type, array('Permalink', 'ID', 'Status', 'Author', 'Timestamp', 'Level', 'Password'))): ?>
						<td class="display-name"><?=$result->cf_display_name?></td>
					<?php else : ?>
						<td class="display-name"><a href="<?=$result->cf_id?>"><?=$result->cf_display_name?></a></td>
					<?php endif;?>
					
					<td><span class="tooltip"><?=\application\utilities\Utility::camelCaseToNormal($result->cf_data_type)?></span><div class="tooltip-content">
			<div class="tooltip-arrow"></div>
			<div class="tooltip-inner">
			<h3><?=\application\utilities\Utility::camelCaseToNormal($result->cf_data_type)?></h3>
			<?php $class = "\\application\\datatypes\\".$result->cf_data_type;
			$class::typeDescription();?>
			</div>
		</div></td>
				</tr>
				<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
				<?php endforeach;?>
			</tbody>
		</table>
		<?php
	}
	
	public function display() {

		?>
		<script type="text/javascript">	
			
			$('.form-tab').live('click', function(e) {
				e.preventDefault();
				if(!$(this).hasClass('selected')) {
					var id = $(this).attr('id');
					var tabId = id.toString().replace('-button', '');
					var tab = $('#' + tabId);
					var tabClass = tab.attr('class');
					$('.'+tabClass).hide();
					tab.show();
					$(this).parent().children('.form-tab').removeClass('selected');
					$(this).addClass('selected');
					
				}
			});
			$('#add-field').click(function(e) {
				e.preventDefault();
				var form = {
					field_display_name:$('input[name="field_display_name"]').val(),
					field_description:$('textarea[name="field_description"]').html(),
					field_data_type:$('select[name="field_data_type"]').val(),
					required:$('input[name="required"]').val()
				};
				console.log(form);
				$.ajax({
					url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure_users&method=newField',
					type:'POST',
					error:function(a,b,c) {
						alert(b);
					},
					data:form,
					dataType:'json',
					beforeSend:function() {
						torchd.ui.showDialog({
							title:'Adding Field...',
							type:'ajax-loader'
						});
					},
					success:function(response) {
						torchd.ui.closeDialog('Adding Field...');
						$('#add-field').parent('li').parent('ul').find('input,textarea,select').val('');
						$('#manage-data-table').replaceWith(response.table);
							
					}
				});
			});	
			
			$('#manage-data-table a').live('click', function(e) {
				var field = $(this).attr('href');
				var title = $(this).html();
				e.preventDefault();
				torchd.ui.showDialog({
					title:'Edit Data Field: ' + title, 
					type:'ajax',
					ajaxUrl:'<?=CN_URL?>admin/?mode=ajax-method&display=configure_users&method=editField&field='+field,
					onSubmit:function(data) {
						console.log(data);
					},
					buttons:[
						{
							id:'submit',
							title:'Submit',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								$.ajax({
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure_users&method=saveField',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-data-table').replaceWith(response.table);
										dialog.close();
										
									}
								});
							}
						},
						{
							id:'cancel',
							title:'Cancel',
							clickAction:function() {
								$(this).data('dialog').close();
							}
						},
						{
							id:'delete',
							title:'Delete Field',
							clickAction:function() {
								var dialog = $(this).data('dialog');
								var form = dialog.content.find('form').serializeObject();
								form.field_delete = true;
								console.log(form);
								$.ajax({
								
									url:'<?=CN_URL?>admin/?mode=ajax-method&display=configure_users&method=saveField',
									type:'POST',
									dataType:'json',
									data:form,
									beforeSend:function() {
										dialog.ajaxLoader();
									},
									success:function(response) {
										$('#manage-data-table').replaceWith(response.table);
										
										dialog.close();
										
									}
								});
							}
						}
					]
				});
			});
		</script>
		<form method="post">
			<section id="general">
				<div class="box">
					<h3>General Settings</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4>Registration Process</h4>
							<ul class="form-fields">
								<li><label><input <?php if($this->UserConfig->getAllowSignup()) echo 'checked="checked"';?> type="checkbox" name="allow_signup"/> Allow users to register on their own.</label></li>
								<li><label><input <?php if($this->UserConfig->getAdminApproval()) echo 'checked="checked"';?> type="checkbox" name="admin_approval"/> Administrators must approve all new user registrations.</label></li>
							</ul>
							<h4>Logging In</h4>
							<h5>After logging in, take user to:</h5>
							<ul class="form-fields">
								<li><label><input <?php if($this->UserConfig->getPostLoginRedirect() == 'home') echo 'checked="checked"';?> type="radio" name="post_login_redirect" value="home"/> The home page.</label></li>
								<li><label><input <?php if($this->UserConfig->getPostLoginRedirect() == 'dashboard') echo 'checked="checked"';?> type="radio" name="post_login_redirect" value="dashboard"/> Their dashboard.</label></li>
								<li><label><input <?php if($this->UserConfig->getPostLoginRedirect() == 'custom') echo 'checked="checked"';?> type="radio" name="post_login_redirect" value="custom"/> Custom link: <input type="text" value="<?=$this->UserConfig->getPostLoginCustom()?>" name="post_login_custom"/></label></li>
							</ul>
						</div>
						<div class="two-column-right">
							<h4>Vetting</h4>
							<ul class="form-fields">
								<li><label><input <?php if($this->UserConfig->getVettingProcess() == 'random_password_email') echo 'checked="checked"';?> type="radio" name="vetting_process" value="random_password_email"/> Password randomly generated and e-mailed to the user.</label></li>
								<li><label><input <?php if($this->UserConfig->getVettingProcess() == 'email_activation') echo 'checked="checked"';?> type="radio" name="vetting_process" value="email_activation"/> User chooses password, but account must be activated by clicking a link sent via e-mail.</label></li>
								<li><label><input <?php if($this->UserConfig->getVettingProcess() == 'no_vetting') echo 'checked="checked"';?>type="radio" name="vetting_process" value="no_vetting"/> User chooses password and account activated immediately (not recommended).</label></li>
							</ul>
							<h4>User Identification</h4>
							<h5>How do you want to identify users on your site?</h5>
							<ul class="form-fields">
								<li><label><input type="radio" <?=($this->UserConfig->getIdentification() == 'email') ? 'checked="checked"' : ''?> name="identification" value="email"/> By E-Mail</label></li>
								<li><label><input type="radio" <?=($this->UserConfig->getIdentification() == 'username') ? 'checked="checked"' : '' ?> name="identification" value="username"/> By Username</label></li>
								<li><label><input type="radio" <?=($this->UserConfig->getIdentification() == 'custom') ? 'checked="checked"' : ''?> name="identification" value="custom"/> Custom Fields:</label>
									<br />
									Type exact field names in curly brackets for dynamic information. <br />E.g. "{Last Name}, {First Name}"
									<input type="text" name="identification_custom" value="<?=$this->UserConfig->getIdentificationCustom()?>"/>
									<br />
									
									<b>Available Fields</b>
									<code>
									<?php $fields = DB()->getVarArray("SELECT `cf_display_name` FROM `cn_content_fields` WHERE `cf_content_type`='0' AND `cf_column` NOT IN ('user_level', 'user_password')");?>
									<?=implode(', ', $fields);?>
									</code>
								</li>
							</ul>
						</div>
						<div class="clearboth"></div>
						
								
					</div>
				</div>
			</section>
			<section id="data" style="display:none;">
				<div class="box">
					<h3>Data</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Data Fields</h3>
							<b>Data fields</b> are handlers for the submission, storage, and display of information for your <b>users</b>. They let you add any sort of data you want, from dates to rich-text editing fields to image galleries. To read about the available data field types and download new ones, click <a href="http://concerto.torchdm.com/data-types/" target="_blank">here</a>.
							</div>
						</div>Add Data Field</h4>
							<ul class="form-fields">
								<li>
									<label>Field Name</label>
									<input type="text" class="big-text wide" name="field_display_name"/>
								</li>
								<li>
									<label>Data Type</label>
									<select name="field_data_type" id="data-type">
										<?php dataTypeSelect();?>
									</select>
									
								</li>
								<li>
									<label><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Field Description</h3>
							Here you can provide a clarification of this data field that users will see on the submission form. E.g. "Check this box if you agree to the terms."
							</div>
						</div>Field Description</label>
									
									<textarea name="field_description" class="wide"></textarea>
								</li>
								
								
								<li>
									<label><input type="checkbox" name="required" value="TRUE"/> Require this field </label>
								</li>
								<li class="last">
									<button id="add-field" class="small-button stretch">Add Field</button>
								</li>
							</ul>
						</div>
						<div class="two-column-right">
							<h4><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>Manage your Data Fields</h3>
							Below you can see all of the data fields attached to your <b>users</b>. You can click on them to change their names and descriptions or to remove them entirely.
							</div>
						</div>Manage Data Fields</h4>
							<?php $this->manageDataTable();?>
						</div>
						<div class="clearboth"></div>
					</div>
				</div>
			</section>
			<section id="user-groups" style="display:none;">
				<div class="box">
					<h3><a class="tooltip question-mark">?</a><div class="tooltip-content">
							<div class="tooltip-arrow"></div>
							<div class="tooltip-inner">
							<h3>User Groups</h3>
							User groups allow you to categorize your users; for now they only help in organization, but soon you will be able to assign custom permissions to each group.
							</div>
						</div>User Groups</h3>
					<div class="box-content">
						<div class="two-column-left">
							<h4>Add Group</h4>
							<ul class="form-fields">
								<li>
									<label>Name</label>
									<input class="big-text wide" type="text" name="interaction_name"/>
								</li>
								<li>
									<input type="submit" id="add-group" name="add_group" class="small-button" value="Add Group"/>
								</li>
							</ul>
						</div>
						<div class="two-column-right">
							<h4>Manage User Groups</h4>
						<table id="manage-interactions-table" class="admin-table" width="100%">
							<thead>
								<tr>
									<th width="100%">Name</th>
								</tr>
							</thead>
							<tbody>
								<?php $style = '';?>
								<?php $results = DB()->getResults("SELECT * FROM `cn_user_groups` ORDER BY `group_name`");
								foreach($results as $result) : 
								
								?>
								<tr<?=$style?>>
									
									<td><a href="<?=$result->group_id?>"><?=$result->group_name?></a></td>
								</tr>
								<?php $style = ($style == ' class="alternate"') ? '' : ' class="alternate"';?>
								<?php endforeach;?>
							</tbody>
						</table>
						</div>
						<div class="clearboth"></div>
					</div>
				</div>
			</section>
			
			</form>
			
			
		</div>
		<div class="clearboth"></div>
	
		
		
		<?php
	}
	
	protected function generatePermalinkStructureOption($structure, $type = null, $group = null) {
		if(!is_array($structure)) $structure = array('name'=>$structure);
		switch($structure['name']) {
			case 'content_identifier':
				?>
				<li data-structure="content_identifier">Content Identifier<a data-structure-name="Content Identifier" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label><input type="radio" name="option" value="id" <?php if($structure['option'] == 'id') echo 'checked="checked"';?>/> Content ID</label>
					<label><input type="radio" name="option" value="title" <?php if($structure['option'] == 'title') echo 'checked="checked"';?>/> Content Title</label>
				</div></li>
				<?php
				break;
			case 'content_type':
				?>
				<li <?php if($type != 'browsing') echo 'class="can-sort"';?> data-structure="content_type"><b><?=$this->ContentType->getPermalink()?></b></li>
				<?php
				break;
			case 'tag_name':
				?>
				<li <?php if($type != 'tag') echo 'class="can-sort"';?> data-structure="tag_name">Tag Name</li>
				<?php
				break;
			case 'first_tag':
				?>
				<li class="can-sort" data-structure="first_tag">First Tag</li>
				<?php
				break;
			case 'day':
				?>
				<li class="can-sort" data-structure="day">Day</li>
				<?php
				break;
			case 'first_tag_from_group':
				$tagGroups = DB()->getResults("SELECT `tag_title`, `tag_id`, `tag_permalink` FROM `cn_tags` WHERE `tag_content_type`='".$this->ContentType->getId()."' AND `tag_type`='group' ORDER BY `tag_title`");
				if(count($tagGroups) > 1) : 
				?>
				<li class="can-sort" data-structure="first_tag_from_group">First Tag From Group<a data-structure-name="First Tag From Group" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label>Choose Tag Group</label>
					<select name="option">
						<?php foreach($tagGroups as $group) : ?>
							<option <?php if($structure['option'] == $group->tag_id) echo 'selected="selected"';?> value="<?=$group->tag_id?>"><?=$group->tag_title?></option>
						<?php endforeach;?>
					</select>
				</div></li>
				<?php
				endif;
				break;
			case 'first_tag_from_other_group':
				$tagGroups = DB()->getResults("SELECT `tag_title`, `tag_id`, `tag_permalink` FROM `cn_tags` WHERE `tag_content_type`='".$this->ContentType->getId()."' AND `tag_type`='group' AND `tag_id` != '$group' ORDER BY `tag_title`");
				if(count($tagGroups) > 1) : 
				?>
				<li class="can-sort" data-structure="first_tag_from_group">First Tag From Other Group<a data-structure-name="First Tag From Other Group" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label>Choose Tag Group</label>
					<select name="option">
						<?php foreach($tagGroups as $group) : ?>
							<option <?php if($structure['option'] == $group->tag_id) echo 'selected="selected"';?> value="<?=$group->tag_id?>"><?=$group->tag_title?></option>
						<?php endforeach;?>
					</select>
				</div></li>
				<?php
				endif;
				break;
			case 'year':
				?>
				<li class="can-sort" data-structure="year">Year</li>
				<?php
				break;
			case 'geneology':
				?>
				<li class="can-sort" data-structure="geneology">Geneology<a data-structure-name="Geneology" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<p>The geneology structure renders all ancestors (set by using the Parent Content field) of the current <b><?=$this->ContentType->getTitle()?></b></p>
					<label><input type="radio" name="option" value="parent" <?php if($structure['option'] == 'parent') echo 'checked="checked"';?>/> All Ancestors up to Parent</label>
					<label><input type="radio" name="option" value="grandparent" <?php if($structure['option'] == 'grandparent') echo 'checked="checked"';?>/> All Ancestors up to Grandparent</label>
				</div></li>
				<?php
				break;
			case 'month':
				?>
				<li class="can-sort" data-structure="month">Month<a data-structure-name="Month" class="permalink-edit-link"></a><div class="permalink-edit-form">
					<label><input type="radio" name="option" value="three-letter" <?php if($structure['option'] == 'three-letter') echo 'checked="checked"';?>/> Three-Letter Representation</label>
					<label><input type="radio" name="option" value="full" <?php if($structure['option'] == 'full') echo 'checked="checked"';?>/> Full Name</label>
				</div></li>
				<?php
				break;
				
		}
	}
}
?>